package com.xmy.cultivate.controller;

import cn.hutool.core.date.DateUtil;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.xmy.cultivate.entity.views.MqCommonDataRs;
import com.xmy.cultivate.respons.RecruitAnalysisRs;
import org.springframework.amqp.core.Message;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.service.*;
import com.xmy.cultivate.util.Code;

import com.xmy.cultivate.util.PageResult;
import com.xmy.cultivate.util.Result;

import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 招聘信息 前端控制器
 * </p>
 *
 * @author hpiggy
 * @since 2024-11-27
 */
//@Controller
@RestController
@Scope("prototype")
@RequestMapping("/api/teacherRecruit")
public class RecruitController extends BaseController{
    @Autowired
    IRecruitCertificateService iRecruitCertificateService;
    @Autowired
    IRecruitService iRecruitService;
    @Autowired
    IDistrictService iDistrictService;
    @Autowired
    IRecruitAuditLogService iRecruitAuditLogService;
    @Autowired
    IStaffService iStaffService;
    @Autowired
    IRecruitImageService iRecruitImageService;
    @Autowired
    IRecruitExperienceService iRecruitExperienceService;
    @Autowired
    IOrganizationService iOrganizationService;
    @Autowired
    ITryJobService iTryJobService;
    @Autowired
    IAreaService iAreaService;

    @Value("${uploadFile.location}")
    private String uploadFileLocation;

    @Value("${aliyun.oss.showImgEndpoint}")
    String showImgEndpoint;

    @Autowired
    IOssUploadService iOssUploadService;

    @Autowired
    IQyWeChartPushService iQyWeChartPushService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    IMqPushService iMqPushService;

    @Autowired
    IStationNeedsService iStationNeedsService;

    @Autowired
    IQuarterService iQuarterService;


    /**手动上传简历*/
    @PostMapping("/upload")
    public Result upload(@RequestParam("files") MultipartFile files,
                         @RequestParam Map<String,String> map) throws IOException {
        try {
            String name = map.get("name");
            String phone = map.get("phone");
            String stations = map.get("stations");
            String stationsId = map.get("stationsId");//adms_station_needs 表的id
            String inviteDateTime = map.get("inviteDateTime");//约面试时间

            //判断手机号不能为空
            if (StringUtils.isEmpty(phone)) {
                return new Result(Code.ERROR, null, "请填写手机号码");
            }
            if (StringUtils.isEmpty(name)) {
                return new Result(Code.ERROR, null, "请填写姓名");
            }
            if (StringUtils.isEmpty(stations)) {
                return new Result(Code.ERROR, null, "请填写岗位意向");
            }
            if (StringUtils.isEmpty(stationsId)) {
                return new Result(Code.ERROR, null, "岗位id不能为空");
            }
            phone = phone.replace(" ","");
            if(phone.length() != 11){
                return new Result(Code.ERROR,"","手机号格式不正确，请检查手机号是否正确");
            }
            //判断上传文件是否为空
            if (files.isEmpty()) {
                return new Result(Code.ERROR, null, "请上传简历");
            }

            QueryWrapper<Recruit> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone",phone);
            long count = iRecruitService.count(queryWrapper);
            if (count > 0) {
                return new Result(Code.ERROR, null, "该手机号已投递过简历，不要重复录入");
            }
            //获取上传文件的后缀名
            String fileType = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
            int recruitFileType;
            switch (fileType) {
                case ".pdf":
                    recruitFileType = 1;
                    break;
                case ".doc":
                case ".docx":
                    recruitFileType = 2;
                    break;
                case ".jpg":
                case ".jpeg":
                case ".png":
                case ".gif":
                    recruitFileType = 3;
                    break;
                default:
                    return new Result(Code.ERROR, null, "不支持的文件类型");
            }



            LocalDate localDate = LocalDate.now();
            //简历目录上传路径
            String certificateDirectoryName = "recruit-file-url" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();
            String uploadUrl = uploadFileLocation + "/" + certificateDirectoryName;
            File file = new File(uploadUrl);
            // 若不存在则创建该文件夹
            if (!file.exists()) {
                file.mkdirs();
            }
            // 把文件的名称设置唯一值，uuid
            //拼接图片
            String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
            String uuid = date + System.currentTimeMillis();
            String filename = uuid + fileType;
            // 完成文件上传
            files.transferTo(new File(uploadUrl, filename));
            String filePath = uploadUrl + "/" + filename;
            String saveName = filename;
            // 上传阿里云
            boolean upImage = iOssUploadService.upFile(filePath, saveName, certificateDirectoryName);
            if (!upImage) {
                return new Result(Code.ERROR, null, "简历上传失败");
            }
            StationNeeds stationNeeds = iStationNeedsService.getById(Long.parseLong(stationsId));
            Quarter quarterNow = iQuarterService.getNowQuarter();

            Recruit recruit = new Recruit();
            recruit.setYearPart(quarterNow.getYearPart());
            recruit.setQuarterNum(quarterNow.getNum());
            recruit.setName(name);
            recruit.setPhone(phone);
            recruit.setStations(stationNeeds.getName()); //岗位意向
            recruit.setStationsId(stationNeeds.getStationId());
            recruit.setStationNeedsId(Long.parseLong(stationsId));
            recruit.setInviterId(this.adminId);
            recruit.setEnterType(2);  //手动录入
            if (StringUtils.isNotBlank(inviteDateTime)){
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime localDateTime = LocalDateTime.parse(inviteDateTime, formatter);

                recruit.setInviteDateTime(localDateTime);
                recruit.setResultStatus(1);
                recruit.setInterviewStatus(1);
            }
            recruit.setRecruitFileType(recruitFileType);
            recruit.setStatus(1);  //符合
            recruit.setRecruitFileUrl(showImgEndpoint+'/'+certificateDirectoryName+'/'+filename);
            boolean save = iRecruitService.save(recruit);
            if (!save) {
                return new Result(Code.ERROR, null, "简历提交失败");
            }
            if (StringUtils.isNotBlank(inviteDateTime)){
                return new Result(Code.SAVE_OK, null, "请到已处理的已邀约里面查看");
            }
            return new Result(Code.SAVE_OK, null, "请到已处理的未邀约里面查看");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.ERROR, null, "文件上传过程中发生错误");
        }

    }
    /**
     * 修改简历
     */
    @PostMapping("/updateRecruitFiles")
    public Result updateImage( @RequestParam Map<String,String> map,
                              @RequestParam(value = "files",required = false) MultipartFile files) throws IOException {
        try {

            String id = map.get("id");
            String stations = map.get("stations");
            String stationsId = map.get("stationsId");
            String name = map.get("name");

            if (StringUtils.isBlank(id)) {
                return new Result(Code.ERROR, null, "请上传简历ID");
            }
            Recruit recruit = iRecruitService.getById(id);
            if (recruit == null){
                return new Result(Code.ERROR, null, "该简历不存在");
            }
//            if (files.isEmpty()) {
//                return new Result(Code.ERROR, null, "请上传图片");
//            }
            if (files != null) {
                if (recruit.getEnterType() != null && recruit.getEnterType() != 2) {
                    return new Result(Code.ERROR, null, "该简历不是手动录入的，不能修改简历");
                }
                //获取上传文件的后缀名
                String fileType = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
                int recruitFileType;
                switch (fileType) {
                    case ".pdf":
                        recruitFileType = 1;
                        break;
                    case ".doc":
                    case ".docx":
                        recruitFileType = 2;
                        break;
                    case ".jpg":
                    case ".jpeg":
                    case ".png":
                    case ".gif":
                        recruitFileType = 3;
                        break;
                    default:
                        return new Result(Code.ERROR, null, "不支持的文件类型");
                }
                LocalDate localDate = LocalDate.now();
                //简历目录上传路径
                String certificateDirectoryName = "recruit-file-url" + "/" + localDate.getYear() + "-" + localDate.getMonthValue();
                String uploadUrl = uploadFileLocation + "/" + certificateDirectoryName;
                File file = new File(uploadUrl);
                // 若不存在则创建该文件夹
                if (!file.exists()) {
                    file.mkdirs();
                }
                // 把文件的名称设置唯一值，uuid
                //拼接图片
                String date = new SimpleDateFormat("yyyyMM").format(System.currentTimeMillis());
                String uuid = date + System.currentTimeMillis();
                String filename = uuid + fileType;
                // 完成文件上传
                files.transferTo(new File(uploadUrl, filename));
                String filePath = uploadUrl + "/" + filename;
                String saveName = filename;
                // 上传阿里云
                boolean upImage = iOssUploadService.upFile(filePath, saveName, certificateDirectoryName);
                if (!upImage) {
                    return new Result(Code.ERROR, null, "简历上传失败");
                }
                //更新简历
                recruit.setRecruitFileType(recruitFileType);
                // 更新数据库中的图片URL
                recruit.setRecruitFileUrl(showImgEndpoint + '/' + certificateDirectoryName + '/' + filename);
            }

            recruit.setStations(stations);
            recruit.setStationsId(Long.parseLong(stationsId));
            recruit.setName(name);

            boolean update = iRecruitService.updateById(recruit);
            if (!update) {
                return new Result(Code.ERROR, null, "简历修改失败");
            }
            return new Result(Code.UPDATE_OK, null, "简历修改成功");
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(Code.ERROR, null, "文件上传过程中发生错误");
        }
    }


    /**
     * 获取简历各项总数据
     */
    @RequestMapping("/countList")
    public Result countList( @RequestParam(value = "startDate",required = false) String startDate,
                             @RequestParam(value = "endDate",required = false) String endDate) {
        try {
            // 一次性查询所有数据
            QueryWrapper<Recruit> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
                // 查询符合条件的数据
                queryWrapper.between("created_at", startDate+" 00:00:00",endDate+" 23:59:59");

            }
            List<Recruit> allRecruits = iRecruitService.list(queryWrapper);

            // 在内存中进行过滤和统计
            //系统未通过
            long systemNotPassCount = allRecruits.stream()
                    .filter(recruit -> recruit.getSystemIsPass() == 0 && recruit.getStatus() == 0 && recruit.getEnterType() == 1)
                    .count();

            //系统已通过
            long systemPassCount = allRecruits.stream()
                    .filter(recruit -> recruit.getSystemIsPass() == 1 && recruit.getStatus() == 0 && recruit.getEnterType() == 1)
                    .count();
            //手动录入
            long manualCount = allRecruits.stream()
                    .filter(recruit ->  recruit.getEnterType() == 2 && recruit.getStatus() == 0)
                    .count();
            //已处理
            long processedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getStatus() != 0)
                    .count();

//            long notInvitedCount = allRecruits.stream()
//                    .filter(recruit -> recruit.getResultStatus() == 0 && recruit.getStatus() != 0)
//                    .count();
            //未邀约
            long notInvitedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getResultStatus() == 0 && recruit.getStatus() == 1)
                    .count();

//            long invitedCount = allRecruits.stream()
//                    .filter(recruit -> recruit.getResultStatus() == 1 && recruit.getStatus() != 0)
//                    .count();
            //已邀约
            long invitedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getResultStatus() == 1 && recruit.getStatus() == 1 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == null)
                    .count();
            //中止
            long endCount = allRecruits.stream()
                    .filter(recruit -> recruit.getResultStatus() == 2 && recruit.getStatus() != 0)
                    .count();
            //已到
            long arrivedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getIsArrive() !=null &&recruit.getIsArrive() == 1)
                    .count();
            //未点评
            long notReviewedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getPassType() == 0 &&recruit.getIsArrive() !=null && recruit.getIsArrive() == 1 )
                    .count();
            //通过
            long passedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getPassType() == 1 && recruit.getIsArrive() !=null && recruit.getIsArrive() == 1 )
                    .count();
            //未通过
            long rejectedCount = allRecruits.stream()
                    .filter(recruit -> recruit.getPassType() == 2 && recruit.getIsArrive() !=null && recruit.getIsArrive() == 1 )
                    .count();
            //试岗自弃
            long tryJobGiveUpCount = allRecruits.stream()
                    .filter(recruit -> recruit.getIsGiveUp() == 1 && recruit.getIsArrive() !=null && recruit.getIsArrive() == 1 )
                    .count();


//            // 将统计结果放入 RecruitList 类
//            RecruitList recruitList = new RecruitList();
//            recruitList.setSystemNotPassCount((int) systemNotPassCount);
//            recruitList.setSystemPassCount((int) systemPassCount);
//            recruitList.setProcessedCount((int) processedCount);
//            recruitList.setNotInvitedCount((int) notInvitedCount);
//            recruitList.setInvitedCount((int) invitedCount);
//            recruitList.setEndCount((int) endCount);
//            recruitList.setArrivedCount((int) arrivedCount);
//
//            recruitList.setNotReviewedCount((int) notReviewedCount);  //未点评
//            recruitList.setPassedCount((int) passedCount);            //通过
//            recruitList.setRejectedCount((int) rejectedCount);        //未通过

            HashMap<String, Object> map = new HashMap<>();
            map.put("manualCount",manualCount);//手动录入
            map.put("systemNotPassCount",systemNotPassCount); //系统未通过
            map.put("systemPassCount",systemPassCount); //系统已通过
            map.put("processedCount",processedCount); //已处理
            map.put("notInvitedCount",notInvitedCount); //未邀约
            map.put("invitedCount",invitedCount); //已邀约
            map.put("endCount",endCount); //中止
            map.put("arrivedCount",arrivedCount); //已到
            map.put("notReviewedCount",notReviewedCount); //未点评
            map.put("passedCount",passedCount); //通过
            map.put("rejectedCount",rejectedCount); //未通过
            map.put("allCount",allRecruits.size());
            map.put("tryJobGiveUpCount",tryJobGiveUpCount);  //试岗自弃
            return new Result(Code.OK,  map, Code.GET_OK_MSG);
        } catch (Exception e) {
            // 异常处理
            e.printStackTrace();
            return new Result(Code.ERROR, null, e.getMessage());
        }
    }

 /**
  * 查询系统已通过,未通过，手动录入的数据
  */
    @RequestMapping("/systemIsPass")
    public Result systemIsPass(
            @RequestParam(value = "systemIsPass",required = false) Integer systemIsPass,  // 1通过，0未通过 2手动录入
            @RequestParam(value = "startDate",required = false) String startDate,
            @RequestParam(value = "endDate",required = false) String endDate,
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize
                                ){
        Page<Recruit> page = new Page<>(pageNum,pageSize);
        QueryWrapper<Recruit>  queryWrapper = new QueryWrapper<>();
        //systemIsPass为2时
        if (systemIsPass == 2){
            queryWrapper.eq("enter_type",2);
        }else {
            queryWrapper.eq("system_is_pass", systemIsPass);
            queryWrapper.eq("enter_type",1);
        }
        queryWrapper.eq("status",0);

        if (StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
            queryWrapper.between("created_at",startDate+" 00:00:00",endDate+" 23:59:59");
        }
        List<Recruit> list = iRecruitService.page(page, queryWrapper).getRecords();
        return new Result(Code.OK, new PageResult<>(list, page.getTotal(), page.getPages()), Code.GET_OK_MSG);

    }

    /**详情 */
    @RequestMapping("/detail")
    public Result detail(@RequestParam(value = "id",required = true) Long id){
        Recruit recruit = iRecruitService.getById(id);
        if ( recruit==null ){
            return new Result(Code.ERROR,"","数据不存在");
        }
        String provinceName = null;
        String cityName = null;
        String countyName = null;
        //得到省市县id去查询省市区名称
        if (recruit.getProvinceId()!=null){
         provinceName = iDistrictService.getById(recruit.getProvinceId()).getDistrict();
        }
        if (recruit.getCityId()!=null) {
             cityName = iDistrictService.getById(recruit.getCityId()).getDistrict();
        }
        if (recruit.getCountyId()!=null){
         countyName = iDistrictService.getById(recruit.getCountyId()).getDistrict();
        }
        //返回省市区名称
        recruit.setProvinceName(provinceName);
        recruit.setCityName(cityName);
        recruit.setCountyName(countyName);

        Integer type = 0;
        Integer status =0; //1拒绝 2接受
       //不符合
        //不符合中止
        if (recruit.getStatus()==2 && recruit.getResultStatus() == 2){
            type = 4;
            status = 2;
        }
        //符合（已处理）未邀约
        if (recruit.getStatus()==1 && recruit.getResultStatus() == 0){
            type = 4;
            status = 1;
        }
        //约面试已邀约
        if (recruit.getInterviewStatus() != null) {
        if (recruit.getResultStatus() == 1&& recruit.getInterviewStatus()==1 ){
            type = 3;
            status = 1;
        }
        //拒面试中止
//        if (recruit.getInterviewStatus() != null) {
            if (recruit.getResultStatus() == 2 && recruit.getInterviewStatus() == 2) {
                type = 3;
                status = 2;
            }
        }
            //符合约面试已到
        if (recruit.getIsArrive()!=null) {
            if (recruit.getStatus() == 1 && recruit.getResultStatus() == 1 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == 1 ) {
                type = 5;
                status = 2;
            }
            //符合约面试未到
            if (recruit.getStatus() == 1 && recruit.getResultStatus() == 2 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == 0 ) {
                type = 5;
                status = 1;
            }
        }
        //获取简历筛选人
        if (recruit.getId() != null) {
                RecruitAuditLog recruitAuditLog = iRecruitAuditLogService.selectRecruitAuditLog(status, recruit.getId(), type);
                if (recruitAuditLog != null) {
                    QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
                    staffQueryWrapper.eq("id", recruitAuditLog.getAuditId());
                    staffQueryWrapper.eq("deleted", 0);
                    staffQueryWrapper.last("limit 1");
                    Staff staff = iStaffService.getOne(staffQueryWrapper);
                    if (staff != null) {
                        recruit.setAuditName(staff.getName());
                    }
                }
        }
        //获取邀约人
       if (recruit.getInviterId() != null) {
               Staff staff = iStaffService.getById(recruit.getInviterId());
               if (staff != null) {
                   //邀约人
                   recruit.setInvitationName(staff.getName());
               }
       }
        //获取面试官
        if (recruit.getEstimateId() != null) {
            Staff staff1 = iStaffService.getById(recruit.getEstimateId());
            if (staff1 != null) {
                recruit.setEstimate(staff1.getName());
            }
        }
        //获取区域
        if (recruit.getAreaId() != null) {
            Area area = iAreaService.getById(recruit.getAreaId());
            if (area != null) {
                recruit.setAreaName(area.getName());
            }
        }
        //获取证书
        QueryWrapper<RecruitCertificate>  queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("recruit_id", id);
        queryWrapper.last("limit 1");
        //获取一条
        RecruitCertificate recruitCertificate = iRecruitCertificateService.getOne(queryWrapper);
        if (recruitCertificate != null){
            recruit.setCertificate(recruitCertificate.getName());
            //获取证书图片
            QueryWrapper<RecruitImage>  recruitImageQueryWrapper = new QueryWrapper<>();
            recruitImageQueryWrapper.eq("recruit_id", id);
            recruitImageQueryWrapper.eq("recruit_type_id", recruitCertificate.getId());
//            recruitImageQueryWrapper.last("limit 1");
            List<RecruitImage> recruitImageList = iRecruitImageService.list(recruitImageQueryWrapper);
            if (!recruitImageList.isEmpty()) {
                //返回集合
                recruit.setRecruitImageList(recruitImageList);
            }
        }
        //获取工作经历
        QueryWrapper<RecruitExperience> recruitExperienceQueryWrapper = new QueryWrapper<>();
        recruitExperienceQueryWrapper.eq("recruit_id", id);
        recruitExperienceQueryWrapper.last("limit 1");

        RecruitExperience recruitExperience = iRecruitExperienceService.getOne(recruitExperienceQueryWrapper);
        if (recruitExperience != null) {
            recruit.setExperience(recruitExperience.getContent());
        }

        return new Result(Code.OK, recruit, Code.GET_OK_MSG);
    }

    /**
     * 符合和未符合 状态 0未处理 1符合，2不符合
     */
    @PutMapping("/updateStatus")
    public Result updateStatus(@RequestBody Recruit recruit){
        Recruit recruit1 = iRecruitService.getById(recruit.getId());
        if (recruit1==null){
            return new Result(Code.ERROR,"","数据不存在");
        }

        Integer resultStatus = 0;
        Integer status = 1;   //1符合，2不符合
        //不符合
        if (recruit.getStatus()==2) {
            //中止
            resultStatus = 2;
            status = 2;
        }
        recruit.setResultStatus(resultStatus);
        boolean update = iRecruitService.updateById(recruit);
        Map<String, String> map = new HashMap<>();
        if (update) {
            //保存到日志表
            RecruitAuditLog recruitAuditLog = new RecruitAuditLog();
            recruitAuditLog.setRecruitId(recruit.getId());
            recruitAuditLog.setStatus(status);
            recruitAuditLog.setType(4);
            recruitAuditLog.setAuditId(this.adminId);
            recruitAuditLog.setContent("");
            iRecruitAuditLogService.save(recruitAuditLog);
        }
        if (recruit.getStatus() == 2){
            map.put("rsType", "2");
            return new Result(Code.OK, map, "不符合的信息请在已处理的中止里查看！");
        }
        map.put("rsType", "1");
        return new Result(Code.OK, map, "符合的信息请在已处理的未邀约里查看！");
    }

    /**
     * 约面试和拒面试 1约面试，2拒面试
     */
    @PutMapping("/updateInterviewStatus")
    public Result updateInterviewStatus(@RequestBody Recruit recruit){
        Recruit recruit1 = iRecruitService.getById(recruit.getId());
        if (recruit1==null){
            return new Result(Code.ERROR,"","数据不存在");
        }
        Integer interviewStatus = 1;  //约面试
        Integer resultStatus = 1;    //已邀约
        Integer status = 1;        //1约面试 ，2拒面试
        //拒面试
        if (recruit.getInterviewStatus()==2){
            interviewStatus = 2;
            //中止邀约
            resultStatus = 2;
            status = 2;

        }
        recruit.setInterviewStatus(interviewStatus);
        recruit.setResultStatus(resultStatus);
        Map<String, String> map = new HashMap<>();

        boolean update = iRecruitService.updateById(recruit);

        if (update){
            //保存到日志表
            RecruitAuditLog recruitAuditLog = new RecruitAuditLog();
            recruitAuditLog.setRecruitId(recruit.getId());
            recruitAuditLog.setStatus(status);
            recruitAuditLog.setType(3);
            if (recruit.getTurnDownContent() != null) {
                recruitAuditLog.setContent(recruit.getTurnDownContent());
            }
            recruitAuditLog.setAuditId(this.adminId);
           iRecruitAuditLogService.save(recruitAuditLog);
       }
        if (recruit.getInterviewStatus() == 2){
            map.put("rsType", "2");
            return new Result(Code.OK, map, "拒面试的信息请在已处理的中止里查看");
        }else if (recruit.getInterviewStatus() == 1){

            //推送给面试官
            String pushTitle = "约面试";
            String inviteDateTime = com.xmy.cultivate.util.DateUtil.dateTimeConversion(recruit.getInviteDateTime().toString().replace("T"," ")+":00");
            String content = inviteDateTime+"有一场面试，面试人："+recruit1.getName();
            iQyWeChartPushService.pushMsgRecruitsDunford(pushTitle,content,recruit1.getId(),4);

            Staff staff = iStaffService.getById(recruit1.getInviterId());
            if (staff != null){
                try {

                    // 延迟队列，距离面试时间5分钟前给邀约人发送面试通知
                    MqCommonDataRs mqCommonDataRs = new MqCommonDataRs();
                    mqCommonDataRs.setType(4);
                    mqCommonDataRs.setId(recruit1.getId());
                    //计算延迟时间秒
                    // 计算当前时间和面试时间之间的间隔，并减去5分钟作为提前提醒的时间
                    LocalDateTime triggerTime = recruit.getInviteDateTime().minusMinutes(5);
                    long delaySeconds = Duration.between(LocalDateTime.now(), triggerTime).getSeconds(); // 获取延迟时间（秒）
                    if (delaySeconds > 0 ) {
                          //推送给邀约人面试5分钟前提醒
                          iMqPushService.pushInterview(mqCommonDataRs, (int) delaySeconds);
//                        rabbitTemplate.send(RabbitMqDelayConfig.DELAY_EXCHANGE, RabbitMqDelayConfig.DELAY_ROUTING_KEY, message);
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        map.put("rsType", "1");
        return new Result(Code.OK, map, "已约面试的信息请在已邀约里查看");
    }

    /**
     * 已到和未到 0未到，1已到，
     */
    @PutMapping("/updateArriveStatus")
    public Result updateArriveStatus(@RequestBody Recruit recruit){
        Recruit recruit1 = iRecruitService.getById(recruit.getId());
        if (recruit1==null){
            return new Result(Code.ERROR,"","数据不存在");
        }
        Integer status = 2;   //1未到  2已到
        //未到
        if (recruit.getIsArrive()==0){
            status = 1;
            //中止
            recruit.setResultStatus(2);
        }
        Map<String, String> map = new HashMap<>();
        boolean update = iRecruitService.updateById(recruit);
        if (update){
            //保存到日志表
            RecruitAuditLog recruitAuditLog = new RecruitAuditLog();
            recruitAuditLog.setRecruitId(recruit.getId());
            recruitAuditLog.setStatus(status);
            recruitAuditLog.setType(5);  //已到未到类型
            if (recruit.getTurnDownContent() != null) {
                recruitAuditLog.setContent(recruit.getTurnDownContent());
            }
            recruitAuditLog.setAuditId(this.adminId);
            iRecruitAuditLogService.save(recruitAuditLog);
        }
        if (recruit.getIsArrive() == 1){
            map.put("rsType", "1");
            return new Result(Code.UPDATE_OK,map,"已到的信息请在已处理的已到里查看");
        }
        map.put("rsType", "0");
        return new Result(Code.UPDATE_OK,map,"未到的信息请在已处理的中止里查看");
    }



    /**
     * 查询已处理招聘信息
     * resultStatus 0未邀约，1已邀约，2中止
     * isArrive 0未到，1已到
     *
     */
    @RequestMapping("/processed")
    public Result processed(
                         @RequestParam(value = "multiState",required = false) String multiState,   //0未邀约，1已邀约，2中止 3已到
                         @RequestParam(value = "name",required = false) String name,    //已邀约人
                         @RequestParam(value = "startDate",required = false) String startDate,  //开始时间
                         @RequestParam(value = "endDate",required = false) String endDate,      //结束时间
                         @RequestParam(value = "passType",required = false) String passType,      //0未点评，1通过，2未通过,3试岗自弃
                         @RequestParam(value = "isToday",required = false) String isToday,      // 1,今日面试
                         @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                         @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize
                                                            ){
        QueryWrapper<Recruit>  queryWrapper = new QueryWrapper<>();
        Page<Recruit> page = new Page<>(pageNum,pageSize);

        if(StringUtils.isNotBlank(multiState)){
            //未邀约
            if (multiState.equals("0")) {
                queryWrapper.eq("result_status", multiState);
                queryWrapper.eq("status", 1);
                queryWrapper.like(StringUtils.isNotBlank(name),"name",name);

            }
            //已邀约
            if (multiState.equals("1")) {
                //今日面试
                Date now = new Date();
                String formattedDate = DateUtil.format(now, "yyyy-MM-dd");
                Date startOfDay = DateUtil.parse(formattedDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
                Date endOfDay = DateUtil.parse(formattedDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
                if (StringUtils.isNotBlank(isToday)) {
                    queryWrapper.eq("result_status", multiState);
                    queryWrapper.eq("interview_status", 1);
                    queryWrapper.eq("status", 1);
                    //查询isArrive为空
                    queryWrapper.isNull("is_arrive");
                    queryWrapper.between("invite_date_time", startOfDay, endOfDay);
                    //名称迷糊筛选
                    queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
//                    queryWrapper.eq(StringUtils.isNotBlank(name),"name",name);
                }if( StringUtils.isBlank(isToday)) {
                    queryWrapper.eq("result_status", multiState);
                    queryWrapper.eq("interview_status", 1);
                    queryWrapper.eq("status", 1);
                    //查询isArrive为空
                    queryWrapper.isNull("is_arrive");
                    queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
                    queryWrapper.notBetween("invite_date_time", startOfDay, endOfDay);
                }
            }
            //中止
            if (multiState.equals("2")) {
                queryWrapper.eq("result_status", multiState);
                queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
            }
            //已到
            if (multiState.equals("3")){
                queryWrapper.eq("is_arrive", 1);
                queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
            }
        }
        //0未点评，1通过，2未通过
        if (StringUtils.isNotBlank(passType)){
            //今日面试
            Date now = new Date();
            String formattedDate = DateUtil.format(now, "yyyy-MM-dd");
            Date startOfDay = DateUtil.parse(formattedDate + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
            Date endOfDay = DateUtil.parse(formattedDate + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
            if (passType.equals("0")) {
                if (StringUtils.isNotBlank(isToday)) {
                    queryWrapper.eq("pass_type", passType);
                    queryWrapper.eq("is_arrive", 1);
                    //queryWrapper.eq("area_status", 0);
                    //今日面试
                    queryWrapper.between("invite_date_time", startOfDay, endOfDay);
                    //名称模糊筛选
                    queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
                }
                if (StringUtils.isBlank(isToday)) {
                    queryWrapper.eq("pass_type", passType);
                    queryWrapper.eq("is_arrive", 1);
                    //queryWrapper.eq("area_status", 0);
                    queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
                    queryWrapper.notBetween("invite_date_time", startOfDay, endOfDay);
                }
            }
            if (passType.equals("1") || passType.equals("2")) {
                queryWrapper.eq("pass_type", passType);
                queryWrapper.eq("is_arrive", 1);
                //queryWrapper.eq("area_status", 1);
                queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
            }
            if (passType.equals("3")) {
                queryWrapper.eq("is_give_up", 1);
                queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
            }
        }
        //时间筛选
        if (StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
            queryWrapper.between("created_at",startDate+" 00:00:00",endDate+" 23:59:59");
        }
        if ("1".equals(passType) || "2".equals(passType)){
            queryWrapper.orderByDesc("invite_date_time");
        }
        if ("0".equals(multiState) || "2".equals(multiState)){
            queryWrapper.orderByDesc("created_at");
        }
        if( "1".equals(multiState)  || "3".equals(multiState)){
            queryWrapper.orderByDesc("invite_date_time");
        }
        if ("3".equals(passType)){
            queryWrapper.orderByDesc("give_up_time");
        }

        List<Recruit> list = iRecruitService.page(page, queryWrapper).getRecords();

        //中止查询简历筛选人

//        if (multiState.equals("2")) {
            if (list != null || list.size() > 0) {
                //遍历集合
                for (Recruit recruit : list) {
                    Integer type = 0;
                    Integer status =0; //1拒绝 2接受
                    //不符合
                    //不符合中止
                    if (recruit.getStatus()==2 && recruit.getResultStatus() == 2){
                        type = 4;
                        status = 2;
                    }
                    //符合（已处理）未邀约
                    if (recruit.getStatus()==1 && recruit.getResultStatus() == 0){
                        type = 4;
                        status = 1;
                    }
                    //约面试已邀约
                    if (recruit.getInterviewStatus() != null) {
                        if (recruit.getResultStatus() == 1&& recruit.getInterviewStatus()==1 ){
                            type = 3;
                            status = 1;
                        }
                        //拒面试中止
                        if (recruit.getResultStatus() == 2 && recruit.getInterviewStatus() == 2) {
                            type = 3;
                            status = 2;
                        }
                    }

                    //符合约面试已到
                    if (recruit.getIsArrive()!=null) {
                        if (recruit.getStatus() == 1 && recruit.getResultStatus() == 1 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == 1 ) {
                            type = 5;
                            status = 2;
                        }
                        //符合约面试未到
                        if (recruit.getStatus() == 1 && recruit.getResultStatus() == 2 && recruit.getInterviewStatus() == 1 && recruit.getIsArrive() == 0 ) {
                            type = 5;
                            status = 1;
                        }
                    }
                    RecruitAuditLog recruitAuditLog = iRecruitAuditLogService.selectRecruitAuditLog(status, recruit.getId(), type);
                    if (recruitAuditLog != null) {
                        QueryWrapper<Staff> staffQueryWrapper = new QueryWrapper<>();
                        staffQueryWrapper.eq("id", recruitAuditLog.getAuditId());
                        staffQueryWrapper.eq("deleted", 0);
                        Staff staff = iStaffService.getOne(staffQueryWrapper);
                        if (staff != null) {
                            recruit.setAuditName(staff.getName());
                        }
                    }
                    QueryWrapper<TryJob> tryJobQueryWrapper = new QueryWrapper<>();
                    tryJobQueryWrapper.eq("recruit_id", recruit.getId());
                    long count = iTryJobService.count(tryJobQueryWrapper);
                    Integer isAllocate = 0;
                    if (count > 0){
                        isAllocate = 1;
                    }
                    recruit.setIsAllocate(isAllocate);

                    //区域
                    if (recruit.getAreaId()!=null){
                        Area area = iAreaService.getById(recruit.getAreaId());
                        if (area!=null){
                            recruit.setAreaName(area.getName());
                        }
                    }

                }
            }
        if (StringUtils.isNotBlank(multiState)){
            for (Recruit recruit : list) {
                recruit.setMultiState(Integer.

                        parseInt(multiState));
            }
        }
        return new Result(Code.OK, new PageResult<>(list, page.getTotal(), page.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 数据统计
     * @param startDate
     * @param endDate
     */
    @RequestMapping("/dataCount")
    public Result dataCount(
            @RequestParam(value = "type",required = false) String type,  //0实时排行  1历史记录
            @RequestParam(value = "recruitStatus",defaultValue = "0") String recruitStatus, //0简历数量，1面试，2面试通过，3面试淘汰， 4试岗，5试岗通过，6试岗淘汰, 7试岗自弃
            @RequestParam(value = "weekNum",defaultValue = "1") Integer weekNum,   //0单日  1一周
            @RequestParam(value = "startDate",required = false) String startDate,
            @RequestParam(value = "endDate",required = false) String endDate
    ){
        //判断开始时间不能为空
//        if (StringUtils.isBlank(startDate)){
//            return new Result(Code.OK, null, "请选择开始时间");
//        }
//            //判断结束时间不能为空
//        if (StringUtils.isBlank(endDate)){
//            return new Result(Code.OK, null, "请选择结束时间");
//        }
        List<HashMap<String, Object>> list = new ArrayList<>();
        //开始时间startDate拼接00:00:00 结束时间endDate23:59:59
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        List<RecruitList> recruitLists = null;
        if (type.equals("0")) {
            //0实时排行
           recruitLists = iRecruitService.countList(startDate, endDate);
        }
        //1历史记录
        if (type.equals("1")) {
            //单日最高记录
            if (weekNum == 0) {
                if (recruitStatus.equals("0") || recruitStatus.equals("1") || recruitStatus.equals("2") || recruitStatus.equals("3") || recruitStatus.equals("7") ) {
                    recruitLists = iRecruitService.getRecruitCount(recruitStatus);
                } else {
                    recruitLists = iRecruitService.getTryJobCount(recruitStatus);
                }
            }
            //一周最高记录
            if (weekNum == 1) {
                if (recruitStatus.equals("0") || recruitStatus.equals("1") || recruitStatus.equals("2") || recruitStatus.equals("3") || recruitStatus.equals("7") ) {
                    recruitLists = iRecruitService.getRecruitCountByWeek(recruitStatus);
                } else {
                    recruitLists = iRecruitService.getTryJobCountByWeek(recruitStatus);
                }

            }
        }
        for (RecruitList recruitList : recruitLists){
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",recruitList.getId());
            map.put("inviterId",recruitList.getInviterId());
            map.put("teacherName",recruitList.getTeacherName());
            map.put("recruitCount",recruitList.getRecruitCount());
            map.put("recruitInterviewCount",recruitList.getRecruitInterviewCount());
            map.put("recruitPassCount",recruitList.getRecruitPassCount());
            map.put("recruitNoPassCount",recruitList.getRecruitNoPassCount());
            map.put("tryJobCount",recruitList.getTryJobCount());
            map.put("tryJobPassCount",recruitList.getTryJobPassCount());
            map.put("tryJobNoPassCount",recruitList.getTryJobNoPassCount());
            map.put("tryJobGiveUpCount",recruitList.getTryJobGiveUpCount());
            map.put("createdAt",recruitList.getCreatedAt());
            map.put("maxDate",recruitList.getMaxDate());
            map.put("maxCount",recruitList.getMaxCount());
            map.put("maxWeekStart",recruitList.getMaxWeekStart());
            map.put("maxWeekEnd",recruitList.getMaxWeekEnd());
            list.add(map);
        }
        return new Result(Code.OK, list, Code.GET_OK_MSG);
    }

    /**数据统计详情
     * @param startDate
     * @param endDate
     * @param recruitStatus
     * @param inviterId
     */
    @GetMapping("/dataCountDetail")
    public Result dataCountDetail(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
            @RequestParam(value = "startDate",required = false) String startDate,
            @RequestParam(value = "endDate",required = false) String endDate,
            @RequestParam(value = "type",required = false) String type,  //0实时排行  1历史记录
            @RequestParam(value = "weekNum",defaultValue = "0") Integer weekNum,   //0单日  1一周
            @RequestParam(value = "recruitStatus",defaultValue = "0") Integer recruitStatus, //0简历数量，1面试，2面试通过，3面试淘汰， 4试岗，5试岗通过，6试岗淘汰, 7试岗自弃
            @RequestParam(value = "inviterId",required = false) String inviterId){
        Page<Recruit> iPage = new Page<>(pageNum,pageSize);
        if (StringUtils.isBlank(inviterId)){
            return new Result(Code.OK, null, "邀约Id不能为空");
        }
//        if (StringUtils.isBlank(startDate)){
//            return new Result(Code.OK, null, "请选择开始时间");
//        }
//        //判断结束时间不能为空
//        if (StringUtils.isBlank(endDate)){
//            return new Result(Code.OK, null, "请选择结束时间");
//        }
        startDate = startDate+" 00:00:00";
        endDate = endDate+" 23:59:59";
        List<HashMap<String, Object>> list = new ArrayList<>();
        QueryWrapper<Recruit> queryWrapper = new QueryWrapper<>();
        if (type.equals("0")) {
            if (recruitStatus != null) {
                if (recruitStatus == 0 || recruitStatus == 1 || recruitStatus == 2 || recruitStatus == 3 || recruitStatus == 7) {
                    if (recruitStatus == 0) {
                        queryWrapper.eq("inviter_id", inviterId);
                        queryWrapper.between("created_at", startDate, endDate);
                    }
                    if (recruitStatus == 1) {
                        queryWrapper.eq("inviter_id", inviterId);
                        //pass_type不等于0
                        queryWrapper.ne("pass_type", 0);
                        queryWrapper.between("invite_date_time", startDate, endDate);
                    }
                    if (recruitStatus == 2) {
                        queryWrapper.eq("inviter_id", inviterId);
                        //pass_type等于1
                        queryWrapper.eq("pass_type", 1);
                        queryWrapper.eq("is_arrive", 1);
                        queryWrapper.between("is_pass_time", startDate, endDate);
                    }
                    if (recruitStatus == 3) {
                        queryWrapper.eq("inviter_id", inviterId);
                        //pass_type等于2
                        queryWrapper.eq("pass_type", 2);
                        queryWrapper.eq("is_arrive", 1);
                        queryWrapper.between("is_pass_time", startDate, endDate);
                    }
                    //试岗自弃
                    if (recruitStatus == 7) {
                        queryWrapper.eq("inviter_id", inviterId);
                        //试岗自弃
                        queryWrapper.eq("is_give_up", 1);
                        queryWrapper.between("give_up_time", startDate, endDate);
                    }
                    iRecruitService.page(iPage, queryWrapper);
                } else {
                    //试岗的详情
                    iRecruitService.dataCountTryJobDetail(iPage, startDate, endDate, inviterId, recruitStatus);
                }
            }
        }else {
            //单日最高记录
            if (weekNum == 0) {
                if (recruitStatus == 0 || recruitStatus == 1 || recruitStatus == 2 || recruitStatus == 3 || recruitStatus == 7) {
                    iRecruitService.oneDayCountDetail(iPage, inviterId, recruitStatus);
                } else {
                    //试岗详情
                    iRecruitService.oneDayCountTryJobDetail(iPage, inviterId, recruitStatus);
                }
            }
            //一周最高记录
            if (weekNum == 1) {
                if (recruitStatus == 0 || recruitStatus == 1 || recruitStatus == 2 || recruitStatus == 3 || recruitStatus == 7) {
                    iRecruitService.oneWeekCountDetail(iPage, inviterId, recruitStatus);
                } else {
                    //试岗详情
                    iRecruitService.oneWeekTryJobCountDetail(iPage, inviterId, recruitStatus);
                }
            }
        }

        for (Recruit recruit : iPage.getRecords()){
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",recruit.getId());
            map.put("inviterId",recruit.getInviterId());
            map.put("name",recruit.getName());
            map.put("phone",recruit.getPhone());
            map.put("created_at",recruit.getCreatedAt());
            map.put("inviteDateTime",recruit.getInviteDateTime());//面试时间
            map.put("isPassTime",recruit.getIsPassTime());//是否通过时间
            map.put("tryDate",recruit.getTryDate());
            map.put("tryAuditDate",recruit.getTryAuditDate());
            map.put("giveUpTime",recruit.getGiveUpTime());
            map.put("maxDate",recruit.getMaxDate());
            list.add(map);
        }
        return new Result(Code.OK, new PageResult<>(list, iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 数据统计
     * @param startDate
     * @param endDate
     */
    //原先接口
//    @RequestMapping("/dataCount")
//    public Result dataCount(
//            @RequestParam(value = "startDate",required = false) String startDate,
//            @RequestParam(value = "endDate",required = false) String endDate
//    ){
//
//        //判断开始时间不能为空
//        if (StringUtils.isBlank(startDate)){
//            return new Result(Code.OK, null, "请选择开始时间");
//        }
//        //判断结束时间不能为空
//        if (StringUtils.isBlank(endDate)){
//            return new Result(Code.OK, null, "请选择结束时间");
//        }
//        HashMap<String, Object> map = new HashMap<>();
//
//        //获取简历份数
//        Long recruitCount = iRecruitService.count(
//                new QueryWrapper<Recruit>()
////                        .eq("inviter_id", this.adminId)
//                        .between("created_at", startDate+" 00:00:00", endDate+" 23:59:59"));
//        //获取面试人数
//        Long recruitInterviewCount = iRecruitService.count(
//                new QueryWrapper<Recruit>()
////                        .eq("inviter_id", this.adminId)
//                        .ne("pass_type",0)
//                        .between("created_at", startDate+" 00:00:00", endDate+" 23:59:59"));
//        //获取面试通过人数
//        Long recruitPassCount = iRecruitService.count(
//                new QueryWrapper<Recruit>()
////                        .eq("inviter_id", this.adminId)
//                        .eq("is_arrive", 1)
//                        .eq("pass_type", 1)
//                        .between("created_at", startDate+" 00:00:00", endDate+" 23:59:59"));
//        //获取面试未通过人数
//        Long recruitNoPassCount = iRecruitService.count(
//                new QueryWrapper<Recruit>()
////                        .eq("inviter_id", this.adminId)
//                        .eq("is_arrive", 1)
//                        .eq("pass_type", 2)
//                        .between("created_at", startDate+" 00:00:00", endDate+" 23:59:59"));
//        //把简历份数和面试人数放进map
//        map.put("recruitCount", recruitCount);
//        map.put("recruitInterviewCount", recruitInterviewCount);
//        map.put("recruitPassCount", recruitPassCount);
//        map.put("recruitNoPassCount", recruitNoPassCount);
//        return new Result(Code.OK, map, Code.GET_OK_MSG);
//    }

    /**
     * 评语/判定
     * @param recruit  未加区域前的接口
     * @return
     */
/*    @PutMapping()
    public Result updateRecruit(@RequestBody Recruit recruit) {
        Recruit recruit1 = iRecruitService.getById(recruit.getId());
        if (recruit1==null){
            return new Result(Code.ERROR,"","不存在该数据");
        }
        //判定
        if (recruit.getPassType() != null){
            if (recruit.getPassType() == 1 || recruit.getPassType() == 2){
                recruit.setIsPassTime(LocalDateTime.now());
            }
        }
        //试岗自放弃
        if (recruit.getIsGiveUp() != null){
            if (recruit.getIsGiveUp() == 1){
                recruit.setGiveUpTime(LocalDateTime.now());
                recruit.setGiveUpContent(recruit.getGiveUpContent());
            }
        }
        boolean update = iRecruitService.updateById(recruit);
        if (update){
            return new Result(Code.OK,"","提交成功");
        }
        return new Result(Code.ERROR,"","提交失败");
    }*/

    /**
     * 评语/判定/区域
     * @param recruit
     * @return
     */
    @PutMapping()
    public Result updateRecruit(@RequestBody Recruit recruit) {
        Recruit recruitOld = iRecruitService.getById(recruit.getId());
        if (recruitOld==null){
            return new Result(Code.ERROR,"","不存在该数据");
        }

        //判定 1、通过 2、未通过
        if (recruit.getDetermineStatus() != null){
            //判定不通过
           if (recruit.getDetermineStatus() == 2){

               recruit.setPassType(2);
               recruit.setIsPassTime(LocalDateTime.now());
               String pushTitle = "面试结果";
//               String inviteDateTime = com.xmy.cultivate.util.DateUtil.dateTimeConversion(recruit.getInviteDateTime().toString().replace("T"," ")+":00");
               String content = "您有一条新的面试结果,面试结果：未通过，面试人："+recruitOld.getName();
               //面试不通过给邀约人推送面试结果
               Staff staff = iStaffService.getById(recruitOld.getInviterId());{
               iQyWeChartPushService.push(staff.getQyWecharId(),pushTitle,content,recruitOld.getId(),5,recruitOld.getInviterId());
               }
           }

        }
        //试岗自放弃
        if (recruit.getIsGiveUp() != null){
            if (recruit.getIsGiveUp() == 1){
                recruit.setGiveUpTime(LocalDateTime.now());
                recruit.setGiveUpContent(recruit.getGiveUpContent());
            }
            Staff staff = iStaffService.getById(recruitOld.getInviterId());
            if (staff != null) {
                if (staff.getQyWecharId() != null) {
                    String pushTitle = "试岗自弃";
                    String content = "您邀约的"+recruitOld.getName()+"求职者，已经自弃";
                    //给邀约人推送试岗自弃
                    iQyWeChartPushService.push(staff.getQyWecharId(), pushTitle, content, recruitOld.getId(), 5, recruitOld.getInviterId());
                }
            }


        }
        //区域
        if (recruit.getAreaId() != null){
            if (recruitOld.getIsComment() != 0 && recruitOld.getDetermineStatus() != 0) {
                recruitOld.setAreaId(recruit.getAreaId());
                //recruit.setAreaId(recruit.getAreaId());
                recruit.setIsPassTime(LocalDateTime.now());
                if (recruitOld.getDetermineStatus() == 1){
                    recruit.setPassType(1);
                    recruit.setIsPassTime(LocalDateTime.now());
                    String pushTitle = "面试结果";
//                    String inviteDateTime = com.xmy.cultivate.util.DateUtil.dateTimeConversion(recruit.getInviteDateTime().toString().replace("T"," ")+":00");
                    String content = "您有一条面试结果，面试结果：通过，面试人："+recruitOld.getName();
                    //面试不通过给邀约人推送面试结果
                    Staff staff = iStaffService.getById(recruitOld.getInviterId());
                    if (staff != null) {
                        //给邀约人推送面试通过结果
                        iQyWeChartPushService.push(staff.getQyWecharId(), pushTitle, content, recruitOld.getId(), 5, recruitOld.getInviterId());
                    }
                }
//                else if (recruit1.getDetermineStatus() == 2){
//                    recruit.setPassType(2);
//                }
            } else {
                return new Result(Code.ERROR,"","提交失败,前面还有流程没走完！");
            }
        }

        boolean update = iRecruitService.updateById(recruit);
        if (update){
            return new Result(Code.OK,"","提交成功");
        }
        return new Result(Code.ERROR,"","提交失败");
    }

    /**简历库列表
     * @param pageNum
     * @param pageSize
     * @param startDate
     * @param endDate
     * @param type 0简历库
     */
    @GetMapping("/resumeList")
    public Result resumeList(
            @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize,
            @RequestParam(value = "startDate",required = false) String startDate,
            @RequestParam(value = "endDate",required = false) String endDate,
            @RequestParam(value = "name",required = false) String name,
            @RequestParam(value = "type",defaultValue = "0") Integer type
    ){
        Page<Recruit> iPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Recruit> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        if (StringUtils.isNotBlank(startDate)&&StringUtils.isNotBlank(endDate)){
            queryWrapper.between("created_at",startDate+" 00:00:00",endDate+" 23:59:59");
        }
        queryWrapper.orderByDesc("created_at");
        iRecruitService.page(iPage,queryWrapper);
        return new Result(Code.OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**获取人事人员列表
     *
     */
    @GetMapping("/getPersonnelList")
    public Result getPersonnelList(@RequestParam(value = "name",required = false) String name){
        List<Staff> personnelList = iStaffService.getPersonnelList(name);
        List<HashMap<String, Object>> list = new ArrayList<>();
        for (Staff staff : personnelList) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("id",staff.getId());
            map.put("name",staff.getName());
            list.add(map);
        }
        return new Result(Code.OK, list, Code.GET_OK_MSG);
    }

    /**修改邀约人
     *
     */
    @PutMapping("/updateInviter")
    public Result updateInviter(@RequestBody Recruit recruit){

        Recruit recruit1 = iRecruitService.getById(recruit.getId());
        if (recruit1==null){
            return new Result(Code.ERROR,"","不存在该数据");
        }
        recruit.setInviterId(recruit.getInviterId());
        boolean update = iRecruitService.updateById(recruit);
        if (update){
            return new Result(Code.OK,"","修改成功");
        }
        return new Result(Code.ERROR,"","修改失败");
    }

    /**重新邀请
     *
     */
    @PostMapping("/reInvite")
    public Result reInvite(@RequestBody Map map){

        String id = (String)map.get("id");
        String inviteDateTime = (String)map.get("inviteDateTime");

        Recruit recruit = iRecruitService.getById(id);
        if (recruit==null){
            return new Result(Code.ERROR,"","不存在该数据");
        }
        Integer status = 1 ; //符合
        Integer resultStatus = 1 ; //已邀约
        Integer interviewStatus = 1 ; //约面试
        String turnDownContent = null;
        Integer isArrive = null;
        boolean updateRecruit = iRecruitService.updateRecruit(id, status, inviteDateTime, resultStatus, turnDownContent, isArrive, interviewStatus);
        if (updateRecruit){
            return new Result(Code.OK,"","请到已处理的已邀约里查看");
        }
        return new Result(Code.ERROR,"","邀请失败");
    }


    /**
     * 简历数据、面试邀约量、面试通过率
     */
    @GetMapping("/resumeData")
    public Result resumeData(
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "dateType", defaultValue = "0") String dateType  //0简历数据  1面试邀约量 2面试通过率
    ) {
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }
        List<RecruitList> recruitList = iRecruitService.resumeData(startDate, endDate, departmentId, stationsId, labourId, type, yearPart, quarterNum, dateType, theirType, subjectsId);

        return new Result(Code.OK, recruitList, Code.GET_OK_MSG);

    }

    /**
     * 简历数据、面试邀约量、面试通过率详情
     *
     * @param startDate
     * @param endDate
     * @param departmentId
     * @param stationsId
     * @param labourId
     * @param type
     * @param inviterId
     */
    @GetMapping("/resumeDataDetails")
    public Result resumeDataDetails(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "inviterId", required = false) String inviterId,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "dateType", defaultValue = "0") String dateType, //0简历数据  1 面试邀约量 2面试通过率
            @RequestParam(value = "recruitStatus", defaultValue = "0") String recruitStatus //0简历，1来面试，2未面试，3面试淘汰， 4面试通过
    ) {
        Page<Recruit> iPage = new Page<>(pageNum, pageSize);
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }
        iRecruitService.resumeDataDetails(iPage, startDate, endDate, departmentId, stationsId, labourId, type, inviterId, yearPart, quarterNum, dateType, recruitStatus, theirType, subjectsId);
        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 面试分析列表
     */
    @GetMapping("/recruitAnalysisList")
    public Result recruitAnalysisList(
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,// 劳动关系
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId

    ) {
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }

        List<RecruitAnalysisRs> recruitList = iRecruitService.getRecruitAnalysisList(yearPart, quarterNum, startDate, endDate, stationsId, departmentId, subjectsId, labourId, type, theirType);

        return new Result(Code.OK, recruitList, "获取数据成功");
    }

    /**
     * 面试分析详情
     */
    @GetMapping("/recruitAnalysisDetails")
    public Result recruitAnalysisDetails(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,// 劳动关系
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "gradeDetailsId", defaultValue = "") String gradeDetailsId
    ) {
        Page<RecruitAnalysisRs> iPage = new Page<>(pageNum, pageSize);

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }

        iRecruitService.getRecruitAnalysisDetails(iPage, yearPart, quarterNum, startDate, endDate, stationsId, departmentId, subjectsId, labourId, gradeDetailsId, type, theirType);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 试岗分析列表
     */
    @GetMapping("/tryJobAnalysisList")
    public Result tryJobAnalysisList(
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,// 劳动关系
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId

    ) {
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }

        List<RecruitAnalysisRs> recruitList = iRecruitService.getTryJobAnalysisList(yearPart, quarterNum, startDate, endDate, stationsId, departmentId, subjectsId, labourId, type, theirType);

        return new Result(Code.OK, recruitList, "获取数据成功");
    }

    /**
     * 试岗分析详情
     */
    @GetMapping("/tryJobAnalysisDetails")
    public Result tryJobAnalysisDetails(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,// 劳动关系
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "gradeDetailsId", defaultValue = "") String gradeDetailsId
    ) {
        Page<RecruitAnalysisRs> iPage = new Page<>(pageNum, pageSize);

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }

        iRecruitService.getTryJobAnalysisDetails(iPage, yearPart, quarterNum, startDate, endDate, stationsId, departmentId, subjectsId, labourId, gradeDetailsId, type, theirType);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    /**
     * 试用分析列表
     */
    @GetMapping("/trialFormAnalysisList")
    public Result trialFormAnalysisList(
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,// 劳动关系
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId

    ) {
        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }

        List<RecruitAnalysisRs> recruitList = iRecruitService.getTrialFormAnalysisList(yearPart, quarterNum, startDate, endDate, stationsId, departmentId, subjectsId, labourId, type, theirType);

        return new Result(Code.OK, recruitList, "获取数据成功");
    }

    /**
     * 试用分析列表
     */
    @GetMapping("/trialFormAnalysisDetails")
    public Result trialFormAnalysisDetails(
            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "yearPart", defaultValue = "") String yearPart,
            @RequestParam(value = "quarterNum", defaultValue = "") String quarterNum,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate,
            @RequestParam(value = "type", defaultValue = "") String type,  //校区招：1， 部门招：2
            @RequestParam(value = "theirType", defaultValue = "") String theirType,  //校区：1， 部门：2
            @RequestParam(value = "departmentId", required = false) String departmentId, //部门id
            @RequestParam(value = "stationsId", required = false) String stationsId,  //岗位id，多选，多个逗号隔开
            @RequestParam(value = "labourId", required = false) String labourId,// 劳动关系
            @RequestParam(value = "subjectsId", defaultValue = "") String subjectsId,
            @RequestParam(value = "gradeDetailsId", defaultValue = "") String gradeDetailsId
    ) {
        Page<RecruitAnalysisRs> iPage = new Page<>(pageNum, pageSize);

        if (StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)) {
            startDate = startDate + " 00:00:00";
            endDate = endDate + " 23:59:59";
        }

        iRecruitService.getTrialFormAnalysisDetails(iPage, yearPart, quarterNum, startDate, endDate, stationsId, departmentId, subjectsId, labourId, gradeDetailsId, type, theirType);

        return new Result(Code.OK, new PageResult(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

}
